package com.learning.JavaSE.workExercise.module4.Task3;

import java.util.concurrent.locks.ReentrantLock;

public class TrainTicket2 {

    private static int tickets = 100;
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Runnable ticketSeller = () -> {
            for (int i = 0; i < 50; i++) {
                sellTicket();
            }
        };
        Thread thread1 = new Thread(ticketSeller);
        Thread thread2 = new Thread(ticketSeller);
        Thread thread3 = new Thread(ticketSeller);

        thread1.start();
        thread2.start();
        thread3.start();
    }

    private static void sellTicket() {
        lock.lock();
        try {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了一张票，剩余：" + --tickets);
            } else {
                System.out.println("没有票了!");
            }
        } finally {
            lock.unlock();
        }
    }
}